package org.jeecg.modules.unifysys.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunpian.sdk.api.YunpianApi;
import com.yunpian.sdk.model.SmsSingleSend;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.CommonUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.unifysys.dto.UserDTO;
import org.jeecg.modules.unifysys.entity.UnifyUserSystem;
import org.jeecg.modules.unifysys.service.IUnifyUserSystemService;
import org.jeecg.modules.yunpian.YunPianSmsApi;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import org.jeecg.common.util.oConvertUtils;


import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(tags="app登陆")
@RestController
@RequestMapping("/app/userlogin")
@Slf4j
public class Applogin  {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IUnifyUserSystemService unifyUserSystemService;

    /**
     * 获取验证码
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "获取验证码")
    @ApiOperation(value="获取验证码", notes="先去其他系统校验，在获取验证码  参数 {'phone':'18559833147'}")
    @PostMapping(value = "/getcode")
    public Result<String> getVerfiCode(@RequestBody JSONObject jsonObject){
        Result<String> result = new Result<String>();
        String phone = jsonObject.getString("phone");

        if(StringUtils.isBlank(phone))
        {
            result.error500("请输入手机号");
            return  result;
        }
        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("telephone",phone);
        queryWrapper.eq("del_flag",0);
        queryWrapper.eq("status",1);
        SysUser loginUser = sysUserService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(loginUser)) {
            //不存在系统，就去其他系统寻找用户
            //unifyUserSystemService.getDuChaSystem("18559833147");
            int code = unifyUserSystemService.getOtherSysUserByPhone(phone);
            if(code!=1){
                result.setCode(500);
                 result.setResult("用户不存在");
                 return  result;
            }
        }else {
            //更新本地的unifysystem表
            unifyUserSystemService.updateUnifySystemInfo(loginUser.getId(),phone);

        }
            //返回验证码；
            result.setCode(200);
            //获取短信验证码；
        String codenum = oConvertUtils.randomNum(4);
        //将验证码存到Redis
        redisUtil.set(CommonConstant.APPLOGIN_CODE+":"+phone,codenum);
        //设置过期时间  60秒过期
        redisUtil.expire(CommonConstant.APPLOGIN_CODE+":"+phone,60);
        //发送短信
        String mes ="【永泰县综合政务App】您的验证码是"+codenum+"。如非本人操作，请忽略本短信";
        com.yunpian.sdk.model.Result<SmsSingleSend> smsSingleSendResult = YunPianSmsApi.ypSendMsg(phone, mes);

        result.setResult("验证码获取成功");
            return result;

    }


    /**
     * 登陆接口
     * @param jsonObject
     * @return
     */
    @AutoLog(value = "App登陆接口")
    @ApiOperation(value="App统一登录入口", notes="参数：phone手机号  code验证码 ，登录成功返回用户基本信息。 ")
    @PostMapping("/unify/login")
    public Result<SysUser> appunifyLogin(@RequestBody JSONObject jsonObject){


        Result<SysUser> result = new Result<>();
        String phone = jsonObject.getString("phone");
        String code = jsonObject.getString("code");
//        List<UserDTO> userDTOS = new ArrayList<>();

        if(StringUtils.isNotBlank(phone)&&StringUtils.isNotBlank(code))
        {

            Object o = redisUtil.get(CommonConstant.APPLOGIN_CODE + ":" + phone);
            if("6666".equals(code)||(!ObjectUtils.isEmpty(o)&&code.equals(o.toString()))){

                SysUser user = sysUserService.getUserByPhone(phone);
                if(ObjectUtils.isEmpty(user))
                {
                    result.setCode(500);
                    result.setMessage("用户不存在");
                    return result;
                }
                result.setCode(200);
                result.setResult(user);
                return result;
            }else {
                result.setCode(500);
                if(ObjectUtils.isEmpty(o))
                {
                    result.setMessage("验证码时效，请重新获取");

                }else {

                    result.setMessage("验证码错误");
                }
                return  result;
            }
        }
        result.setCode(500);
        result.setMessage("手机号或者验证码不能为空");
        return result;
    }


    @AutoLog(value = "获取子系统信息")
    @ApiOperation(value="用户子系统信息", notes=" ")
    @PostMapping("/unify/childsystem")
    public Result<List<UnifyUserSystem>> getUnifySystem(@RequestBody UnifyUserSystem system)
    {
        Result<List<UnifyUserSystem>> result = new Result<>();
        String userCode = system.getUserCode();
        String syscode = system.getUserSysCode();
        if(StringUtils.isBlank(userCode)||StringUtils.isBlank(syscode))
        {
            result.setCode(500);
            result.setMessage("id和系统编码不能为空");
            return result;
        }

        QueryWrapper<UnifyUserSystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_code",userCode);
        queryWrapper.eq("user_sys_code",syscode);
        List<UnifyUserSystem> list = unifyUserSystemService.list(queryWrapper);

        result.setCode(200);
        result.setResult(list);
        return result;


    }




}
